package com.example.dollarShipping.service;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.dollarShipping.entity.*;
import com.example.dollarShipping.mapper.*;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import jakarta.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CarrierService {
    @Resource
    CarrierMapper carrierMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    TruckMapper truckMapper;
    @Resource
    CarrierDriverMapper carrierDriverMapper;
    @Resource
    TruckOrderMapper truckOrderMapper;
    @Resource
    ShippingOrderService shippingOrderService;
    @Resource
    OperationRecordMapper operationRecordMapper;
    public List<Carrier> getInfo(String name) {
        QueryWrapper wrapper = new QueryWrapper();
        if(name!=null && name!="") wrapper.like("name", name);
        List<Carrier> cl = carrierMapper.selectList(wrapper);
        cl.stream().map(carrier -> moreDetail(carrier)).collect(Collectors.toList());
        return cl;
    }

    public Carrier findCarrier(Long id) {
        Carrier c = carrierMapper.selectById(id);
        c = moreDetail(c);
        return c;
    }

    private Carrier moreDetail(Carrier c){
        User user = userMapper.selectById(c.getUserId());
        c.setUser(user);
        List<User> driverList = userMapper.selectList(new QueryWrapper<User>().inSql("id", "SELECT driver_id FROM carrier_driver WHERE carrier_id = " + c.getId()));
        c.setDrivers(driverList);
        List<Truck> truckList = truckMapper.selectList(new QueryWrapper<Truck>().eq("carrier_id", c.getId()));
        c.setTrucks(truckList);
        return c;
    }

    public List<User> findFreeDrivers(Long id) {
        List<User> dl = userMapper.selectList(new QueryWrapper<User>().inSql("id", "SELECT driver_id FROM carrier_driver WHERE state = 0 and carrier_id = " + id));
        dl.forEach(d->{
            d.setPassword("1");
            d.setEmail("1");
        });
        return dl;
    }

    public List<Truck> findFreeTrucks(Long id) {
        return truckMapper.selectList(new QueryWrapper<Truck>().eq("carrier_id", id).eq("state",0));
    }

    public int update(Carrier c) {
        return carrierMapper.updateById(c);
    }

    public int delete(Long id) {
        int f1 = userMapper.delete(new QueryWrapper<User>().inSql("id", "SELECT driver_id FROM carrier_driver WHERE carrier_id = " + id));
        int f2 = carrierMapper.deleteById(id);
        if(f1<0||f2<0) return 1;
        else return -1;
    }
    public void createTruckOrder(TruckOrder t){
        //插入派车单
        t.setCreateTime(new Date());
        truckOrderMapper.insert(t);
        ShippingOrder s = shippingOrderService.selectById(t.getOrderId());
        //更新货车和司机状态
        Truck truck = truckMapper.selectById(t.getTruckId());
        truck.setState(1);
        CarrierDriver cd = new CarrierDriver(t.getCarrierId(),t.getDriverId());
        cd.setState(1);
        truckMapper.updateById(truck);
        carrierDriverMapper.update(cd,new UpdateWrapper<CarrierDriver>().eq("driver_id",t.getDriverId()));
        //更新货运单状态
        List<TruckOrder> truckOrders = truckOrderMapper.selectList(new QueryWrapper<TruckOrder>().eq("order_id",s.getId()));
        Float weight = 0F;
        for (TruckOrder item:truckOrders){
            weight+=item.getWeight();
        }
        if (weight>=s.getWeight()){
            s.setState(3);
            shippingOrderService.updateOrder(s);
        }
        //操作记录
        Carrier c = carrierMapper.selectById(t.getCarrierId());
        OperationRecord task = new OperationRecord(1,t.getOrderId(),2,c.getUserId(),new Date());
        operationRecordMapper.insert(task);
    }

    public void addTruck(Truck truck) {
        truckMapper.insert(truck);
    }

    public List<ShippingOrder> getShippingOrder(Integer state,Long carrierId) {
        List<ShippingOrder> shippingOrder = shippingOrderService.getShippingOrder(null,state,carrierId);
        shippingOrder.stream().map(s -> moreOrderDetail(s)).collect(Collectors.toList());
        return shippingOrder;
    }

    private ShippingOrder moreOrderDetail(ShippingOrder s){
        List<OperationRecord> sl = operationRecordMapper.selectList(new QueryWrapper<OperationRecord>().eq("type",1).eq("order_id",s.getId()));
        List<TruckOrder> truckOrder = truckOrderMapper.selectList(new QueryWrapper<TruckOrder>().eq("order_id",s.getId()));
        for(TruckOrder t:truckOrder){
            User driver =userMapper.selectById(t.getDriverId());
            Truck truck = truckMapper.selectById(t.getTruckId());
            t.setDriver(driver.getRealName());
            String truckName = truck.getNumber()+"(dwt:"+truck.getWeight()+")";
            t.setTruck(truckName);
            List<OperationRecord> tl = operationRecordMapper.selectList(new QueryWrapper<OperationRecord>().eq("type",2).eq("order_id",t.getId()));
            t.setOperationRecords(tl);
        }
        s.setOperationRecords(sl);
        s.setTruckOrder(truckOrder);
        return s;
    }

    public void changeState(Long carrierId, Long id, Long operator) {
        ShippingOrder s = shippingOrderService.selectById(id);
        Carrier c = carrierMapper.selectById(carrierId);
        s.setState(2);
        s.setCarrierId(carrierId);
        s.setLogisticsCost((double) (c.getUnitPrice()*s.getDistance()*s.getWeight()));
        shippingOrderService.updateOrder(s);
        OperationRecord task = new OperationRecord(1,id,1,operator,new Date());
        operationRecordMapper.insert(task);
    }


    public ShippingOrder findShippingOrder(Long id) {
        return shippingOrderService.findShippingOrder(id);
    }
}
